package com.sam.im.heiqun.uis.fragments;

import android.app.NotificationManager;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;

import com.google.gson.Gson;
import com.sam.im.heiqun.R;
import com.sam.im.heiqun.app.App;
import com.sam.im.heiqun.constant.Constant;
import com.sam.im.heiqun.entities.AiteEntivity;
import com.sam.im.heiqun.entities.ImFriendEntivity;
import com.sam.im.heiqun.entities.ImGroupEntivity;
import com.sam.im.heiqun.entities.ImMessage;
import com.sam.im.heiqun.entities.MessageEntivity;
import com.sam.im.heiqun.entities.TipEntity;
import com.sam.im.heiqun.entities.UserEntivity;
import com.sam.im.heiqun.entities.ValidateEntivity;
import com.sam.im.heiqun.nets.PGService;
import com.sam.im.heiqun.uis.activities.AccountActivity;
import com.sam.im.heiqun.uis.activities.ChatActivity;
import com.sam.im.heiqun.uis.activities.ChatGroupActivity;
import com.sam.im.heiqun.uis.activities.GroupTransActivity;
import com.sam.im.heiqun.uis.activities.MainActivity;
import com.sam.im.heiqun.uis.activities.NewFriendsActivity;
import com.sam.im.heiqun.uis.adapters.MessageAdpter;
import com.sam.im.heiqun.uis.presenters.MsgLinearLayoutManager;
import com.sam.im.heiqun.utils.EventBusTypeObject;
import com.sam.im.heiqun.utils.ToolsUtils;
import com.yuyh.library.nets.callbacks.AbsAPICallback;
import com.yuyh.library.nets.exceptions.ApiException;
import com.yuyh.library.uis.fragments.BaseFragment;
import com.yuyh.library.utils.EventBusType;
import com.yuyh.library.utils.toast.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

import butterknife.BindView;

/**
 * <p>
 * interface.
 * 消息界面
 */
public class MessageFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener, MessageAdpter.MessageListClickListener, MessageAdpter.OncontentClicklistener {

    private static final String TAG = "MessageFragment";
    @BindView(R.id.message_list)
    RecyclerView messageList;
    private MessageAdpter mMessageAdpter;
    private List<MessageEntivity> messageEntivities = new ArrayList<>();
    private List<MessageEntivity> messageEntivities2 = new ArrayList<>();
    private UserEntivity mUserEntivity;
    private int num = 0;
    private PopupMenu popupMenu; // 消息弹框菜单
    private Menu menu;
    private PGService mPGservice;

    @Override
    public void onRefresh() {
    }

    @Override
    public int getContentViewId() {
        return R.layout.fragment_message;
    }

    @Override
    public void onResume() {//这里检测是否还有@消息
        super.onResume();
        // searchAiteNums();
    }

    /*
        检查@消息数
    */
    private void searchAiteNums() {
        Iterator<AiteEntivity> all = AiteEntivity.findAll(AiteEntivity.class);
        if (all.hasNext()) {//这里表示列表中没有数据了
            Log.i("info", "有@消息了");
            mMessageAdpter.setAiting(true);
        } else {
            Log.i("info", "没有@消息了");
            mMessageAdpter.setAiting(false);
        }
    }

    @Override
    public void init(Bundle savedInstanceState) {
        mPGservice = PGService.getInstance();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);//订阅
        }
        messageList.setLayoutManager(new MsgLinearLayoutManager(getActivity()));
        mMessageAdpter = new MessageAdpter(getActivity());
        mMessageAdpter.setItemClickListener(this);
        messageList.setAdapter(mMessageAdpter);
        //messageList.addItemDecoration(new DividerItemDecorationUtils(getActivity(), LinearLayoutManager.HORIZONTAL, 1, getResources().getColor(R.color.black_divider)));
        mUserEntivity = ToolsUtils.getUser();
        Log.i(TAG, "showNum: ==goto===getDataAtThread===004=======");
        getDataAtThread(null);
        mMessageAdpter.setOncontentClicklistener(this);
        //取消所有通知
        // NotificationManager nm = (NotificationManager) getContext().getSystemService(getContext().NOTIFICATION_SERVICE);
        // nm.cancelAll();
    }

    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行 接收到消息进行处理
    public void onAiteEvent(String string) {
     /* if (string.equals("isnoaite")){
          mMessageAdpter.setAiting(false);
      }else if (string.equals("isaiting")){
          mMessageAdpter.setAiting(true);
      }*/
    }

    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行 接收到消息进行处理
    public void onGroupHeadEvent(EventBusTypeObject obt) {
        if (null != obt) {
            if (obt.getType() == EventBusType.REFRESH_LIST_GROUP_HEAD) {
                if (null != messageEntivities2 && messageEntivities2.size() > 0) {
                    for (int i = 0; i < messageEntivities2.size(); i++) {
                        MessageEntivity messageEntivity = messageEntivities2.get(i);
                        if (obt.getUid().equals("" + messageEntivity.getDestid())) {
                            messageEntivity.setImgUrl(obt.getSessiontype());
                            messageEntivities2.set(i, messageEntivity);
                            mMessageAdpter.notifyItemChanged(i);
                            return;
                        }
                    }
                }
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行 接收到消息进行处理
    public void onImMessageEvent(MessageEntivity messageEntivity) {

        getDataAtThread(messageEntivity);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);//解除订阅
    }

    public void getDataAtThread(final MessageEntivity messageEntivity) {
        Log.i(TAG, "getDataAtThread: -----------0001------");
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (messageEntivity == null) {//没有新消息从数据库查询
                    if (mUserEntivity == null) {
//                        List<UserEntivity> userEntivities = UserEntivity.find(UserEntivity.class, "login_state=? and mobile =?", "1", mUserEntivity.getMobile());
                        List<UserEntivity> userEntivities = UserEntivity.find(UserEntivity.class, "login_state=? and mobile =?", "1", App.phone);
                        if (userEntivities.size() > 0) {
                            mUserEntivity = userEntivities.get(0);
                        }
                    }
                    if (null == mUserEntivity) return;
                    Log.i("info","消息页面显示值"+messageEntivity);
                    List<MessageEntivity> topList = MessageEntivity.find(MessageEntivity.class,
                            "fromid=? and istop=? and type!=? and type!=? and type!=? and type!=? and type!=? and type!=?",
                            new String[]{mUserEntivity.getId() + "",
                                    Constant.TOP_MAN + "",
                                    Constant.MESSAGE_TYPR_TRANSFOR_ISCOME + "",
                                    Constant.NOTICE_OF_APPLY_FRIEND + "",
                                    Constant.MESSAGE_TYPR_APPLY_FRIEND + "",
                                    Constant.MESSAGE_TYPR_TOPAYFOR + "",
                                    Constant.MESSAGE_TYPR_GROUP_TRANS_ME + "",
                                    Constant.MESSAGE_GROUP_ADD_APPLY+""}, null, "time desc", null);
                    List<MessageEntivity> notTopList = MessageEntivity.find(MessageEntivity.class,
                            "fromid=? and istop=? and type!=? and type!=? and type!=? and type!=? and type!=? and type!=?"
                            , new String[]{mUserEntivity.getId() + "",
                                    Constant.TOP_NOT_MAN + "",
                                    Constant.MESSAGE_TYPR_TRANSFOR_ISCOME + "",
                                    Constant.NOTICE_OF_APPLY_FRIEND + "",
                                    Constant.MESSAGE_TYPR_APPLY_FRIEND + "",
                                    Constant.MESSAGE_TYPR_TOPAYFOR + "",
                                    Constant.MESSAGE_TYPR_GROUP_TRANS_ME + "",
                                    Constant.MESSAGE_GROUP_ADD_APPLY+""}, null, "time desc", null);
                    //MESSAGE_TYPR_GROUP_TRANS_ME  群通知
                    //好友申请
                    List<MessageEntivity> sysList = MessageEntivity.find(MessageEntivity.class, "fromid=? and (type=? or type=?)", new String[]{mUserEntivity.getId() + "", Constant.MESSAGE_TYPR_APPLY_FRIEND + "", Constant.NOTICE_OF_APPLY_FRIEND + ""}, null, "time desc", null);
                    List<MessageEntivity> sysList2 = MessageEntivity.find(MessageEntivity.class, "uniqueness=? and type=? ", new String[]{ToolsUtils.getMyUserId() + "___", Constant.MESSAGE_TYPR_TRANSFOR_ISCOME + ""}, null, "time desc", null);
                    List<MessageEntivity> sysList3 = MessageEntivity.find(MessageEntivity.class, "uniqueness=? and type=? ", new String[]{ToolsUtils.getMyUserId() + "___", Constant.MESSAGE_TYPR_TOPAYFOR + ""}, null, "time desc", null);
                    List<MessageEntivity> sysList4 = MessageEntivity.find(MessageEntivity.class, "uniqueness=? and type=? ", new String[]{ToolsUtils.getMyUserId() + "___", Constant.MESSAGE_TYPR_GROUP_TRANS_ME + ""}, null, "time desc", null);
                    List<MessageEntivity> sysList5 = MessageEntivity.find(MessageEntivity.class, "uniqueness=? and type=? ", new String[]{ToolsUtils.getMyUserId() + "___", Constant.MESSAGE_GROUP_ADD_APPLY + ""}, null, "time desc", null);
                    messageEntivities.clear();
                    if (sysList.size() > 0) {
                        messageEntivities.add(sysList.get(sysList.size() - 1));
                    }
                    if (sysList2.size() > 0) {
                        Log.i("info", "===" + sysList2.toString() + "\n" + ToolsUtils.getMyUserId());
                        messageEntivities.add(sysList2.get(sysList2.size() - 1));
                    }
                    if (sysList3.size() > 0) {
                        messageEntivities.add(sysList3.get(sysList3.size() - 1));
                    }
                    if (sysList4.size() > 0) {
                        if (sysList5.size() > 0){
                            try {
                                MessageEntivity messageEntivity4 = sysList4.get(sysList4.size() - 1);
                                MessageEntivity messageEntivity5 = sysList5.get(sysList5.size() - 1);
                                if (messageEntivity5.getTime() > messageEntivity4.getTime()){
                                    Log.i("info", "run: ===================看看这个001====01==========="+(sysList5.get(sysList5.size() - 1)).getContent());
                                    messageEntivities.add(sysList5.get(sysList5.size() - 1));
                                }else {
                                    Log.i("info", "run: ===================看看这个001====02==========="+(sysList4.get(sysList4.size() - 1)).getContent());
                                    messageEntivities.add(sysList4.get(sysList4.size() - 1));
                                }
                            }catch (Exception e){
                                e.printStackTrace();
                                Log.i("info", "run: ===================看看这个001====03==========="+(sysList4.get(sysList4.size() - 1)).getContent());
                                messageEntivities.add(sysList4.get(sysList4.size() - 1));
                            }
                        }else {
                            Log.i("info", "run: ===================看看这个001====04==========="+(sysList4.get(sysList4.size() - 1)).getContent());
                            messageEntivities.add(sysList4.get(sysList4.size() - 1));
                        }
                    }else
                    if (sysList5.size() > 0) {
                        Log.i("info", "run: ===================看看这个001==============="+(sysList5.get(sysList5.size() - 1)).getContent());
                        messageEntivities.add(sysList5.get(sysList5.size() - 1));
                    }
                    messageEntivities.addAll(topList);
                    messageEntivities.addAll(notTopList);
                    //  Log.i("info","messagesize=="+messageEntivities.toString()+"\n"+sysList.size()+"\n"+topList.size()+"\n"+notTopList.size());
                } else {
                    if (messageEntivity.getFromType() == Constant.BLACK_BROADCAST_MESSAGE_REFRESH) {//删除好友，移除本地数据库数据
                        messageEntivities = MessageEntivity.find(MessageEntivity.class, "fromid=? and destid=?", new String[]{messageEntivity.getFromid() + "", messageEntivity.getDestid() + ""}, null, "time desc", null);
                        if (messageEntivities.size() > 0) {
                            MessageEntivity.delete(messageEntivities.get(0));
                            messageEntivities.remove(messageEntivities.get(0));
                        }
                    }

                    // messageEntivities = MessageEntivity.find(MessageEntivity.class, "fromid=?", new String[]{messageEntivity.getFromid() + ""}, null, "time desc", null);
                    List<MessageEntivity> topList = MessageEntivity.find(MessageEntivity.class, "fromid=? and istop=?  and type!=? and type!=? and type!=? and type!=? and type!=?"
                            , new String[]{messageEntivity.getFromid() + "", Constant.TOP_MAN + "", Constant.NOTICE_OF_APPLY_FRIEND + "", Constant.MESSAGE_TYPR_APPLY_FRIEND + "", Constant.MESSAGE_TYPR_TRANSFOR_ISCOME + ""
                                    , Constant.MESSAGE_TYPR_TOPAYFOR + "", Constant.MESSAGE_GROUP_ADD_APPLY+""}, null, "time desc", null);
                    List<MessageEntivity> notTopList = MessageEntivity.find(MessageEntivity.class,
                            "fromid=? and istop=?  and type!=? and type!=? and type!=? and type!=? and type!=? and type!=? and type!=?"
                            , new String[]{
                            messageEntivity.getFromid() + "", Constant.TOP_NOT_MAN + "", Constant.NOTICE_OF_APPLY_FRIEND + "",
                                    Constant.MESSAGE_TYPR_APPLY_FRIEND + "", Constant.MESSAGE_TYPR_TRANSFOR_ISCOME + "",Constant.MESSAGE_TYPR_GROUP_TRANS_ME + ""
                                    , Constant.MESSAGE_TYPR_TOPAYFOR + "", Constant.MESSAGE_GROUP_ADD_APPLY+"",Constant.MESSAGE_TYPR_GROUP_SET_MANAGER+""}, null, "time desc", null);

                    //好友申请  (这里多了支付消息来自系统一起取出来)
                    List<MessageEntivity> sysList = MessageEntivity.find(MessageEntivity.class, "fromid=? and (type=? or type=?)", new String[]{messageEntivity.getFromid() + "", Constant.NOTICE_OF_APPLY_FRIEND + "", Constant.MESSAGE_TYPR_APPLY_FRIEND + ""}, null, "time desc", null);
                    List<MessageEntivity> sysList2 = MessageEntivity.find(MessageEntivity.class, "uniqueness=? and type=? or type=? ", new String[]{ToolsUtils.getMyUserId() + "___", Constant.MESSAGE_TYPR_TRANSFOR_ISCOME + "", Constant.MESSAGE_TYPR_TOPAYFOR + ""}, null, "time desc", null);
                    List<MessageEntivity> sysList3 = MessageEntivity.find(MessageEntivity.class, "uniqueness=? and type=? ", new String[]{ToolsUtils.getMyUserId() + "___", Constant.MESSAGE_TYPR_GROUP_TRANS_ME + ""}, null, "time desc", null);
                    List<MessageEntivity> sysList4 = MessageEntivity.find(MessageEntivity.class, "uniqueness=? and type=? ", new String[]{ToolsUtils.getMyUserId() + "___", Constant.MESSAGE_GROUP_ADD_APPLY + ""}, null, "time desc", null);

                    messageEntivities.clear();
                    if (sysList.size() > 0) {
                        messageEntivities.add(sysList.get(sysList.size() - 1));
                    }
                    // Log.i("info","syslist2=="+sysList2.size());
                    if (sysList2.size() > 0) {
                        messageEntivities.add(sysList2.get(sysList2.size() - 1));
                    }
                    Log.i("info", "syslist3==" + sysList3.size());
                    if (sysList3.size() > 0) {
                        if (sysList4.size() > 0){
                            try {
                                MessageEntivity messageEntivity3 = sysList3.get(sysList3.size() - 1);
                                MessageEntivity messageEntivity4 = sysList4.get(sysList4.size() - 1);
                                if (messageEntivity4.getTime() >messageEntivity3.getTime()){
                                    Log.i("info", "run: ===================看看这个002===01============"+(sysList4.get(sysList4.size() - 1)).getContent());
                                    messageEntivities.add(sysList4.get(sysList4.size() - 1));
                                }else {
                                    messageEntivities.add(sysList3.get(sysList3.size() - 1));
                                    Log.i("info", "run: ===================看看这个002===02============"+(sysList3.get(sysList3.size() - 1)).getContent());
                                }
                            }catch (Exception e){
                                e.printStackTrace();
                                Log.i("info", "run: ===================看看这个002===03============"+(sysList3.get(sysList3.size() - 1)).getContent());
                                messageEntivities.add(sysList3.get(sysList3.size() - 1));
                            }
                        }else {
                            messageEntivities.add(sysList3.get(sysList3.size() - 1));
                            Log.i("info", "run: ===================看看这个002===04============"+(sysList3.get(sysList3.size() - 1)).getContent());
                        }
                    }else
                    if (sysList4.size() > 0) {
                        Log.i("info", "run: ===================看看这个002==============="+(sysList4.get(sysList4.size() - 1)).getContent());
                        messageEntivities.add(sysList4.get(sysList4.size() - 1));
                    }
                    messageEntivities.addAll(topList);
                    messageEntivities.addAll(notTopList);
                    //  Log.i("info","messagesize=="+messageEntivities.toString());

                }

                /**
                 * 强行移除messageEntivities中的异常数据
                 */
                List<MessageEntivity> tempMessageEntivities = new ArrayList<>();
                for (int i = 0; i < messageEntivities.size(); i++) {
                    MessageEntivity messageEnt = messageEntivities.get(i);
                    if (messageEnt != null)
                        if (messageEnt.getFromType() == Constant.FROM_TYPE_MAM) {//单人聊天
                            if (messageEnt.getDestid() == 0 || (messageEnt.getDestid() + "").equals("null") || (messageEnt.getDestid() + "").equals("")) {
                                //messageEntivities.remove(i);
                                continue;
                            }
                            /**
                             * 下边代码是删除会话列表中不是我的好友的聊天会话，如果后期可以陌生人聊天的话，这里再放开
                             */
                            List<ImFriendEntivity> friendEntivityList = ImFriendEntivity.find(ImFriendEntivity.class, "id=?", new String[]{"" + messageEnt.getDestid()});
                            if (null == friendEntivityList || friendEntivityList.size() <= 0
//                                || "17192".equals(""+messageEnt.getDestid())
                                    ) {
                                messageEnt.delete();
                                /**
                                 * 这是不让弹通知栏
                                 */
                                NotificationManager notificationManager = (NotificationManager) getActivity().getSystemService(getActivity().NOTIFICATION_SERVICE);
                                int id = (int) messageEnt.getDestid();
                                notificationManager.cancel(id);//注销单人聊天
                                continue;
                            }
                        }
                    if (messageEnt.getFromType() == Constant.FROM_TYPE_GROUP) {//群组中出现问题
                        ImGroupEntivity groupEntivity = ImGroupEntivity.findById(ImGroupEntivity.class, messageEnt.getDestid());
                        if (groupEntivity == null || groupEntivity.getId() == null || (groupEntivity.getId() + "").equals("null") || (groupEntivity.getId() + "").equals("")) {
                            messageEnt.delete();
                            // messageEntivities.remove(i);
                            continue;
                        }
                    }
                    tempMessageEntivities.add(messageEnt);
                }
                messageEntivities.clear();
                messageEntivities.addAll(tempMessageEntivities);
                num = 0;
                List<MessageEntivity> messageEntivities = MessageEntivity.find(MessageEntivity.class, "fromid=?", new String[]{ToolsUtils.getMyUserId() + ""});

                if (null != messageEntivities && messageEntivities.size() > 0) {
                    for (int i = 0; i < messageEntivities.size(); i++) {
                        //Log.i("info","这里messageentivity=="+messageEntivities.get(i));
                        num = num + Integer.parseInt("" + messageEntivities.get(i).getMessageNum());

                    }
                }

                EventBus.getDefault().post(Constant.BLACK_MESSAGE_REFRESH);//通知刷新界面
            }
        }).start();
    }

    /**
     * 降序
     * -1和0都不交换
     * 1交换
     */
    public static final class ComparatorValues implements Comparator<MessageEntivity> {
        @Override
        public int compare(MessageEntivity object1, MessageEntivity object2) {
            long m1 = 0;
            long m2 = 0;
            try {
                m1 = object1.getTime();
                m2 = object2.getTime();
            } catch (Exception e) {
                e.printStackTrace();
            }

            if (object1.getType() == Constant.MESSAGE_TYPR_APPLY_FRIEND || object1.getType() == Constant.NOTICE_OF_APPLY_FRIEND) {
                return -1;
            } else if (object2.getType() == Constant.MESSAGE_TYPR_APPLY_FRIEND || object2.getType() == Constant.NOTICE_OF_APPLY_FRIEND) {
                return 1;
            } else if (object1.getType() == Constant.MESSAGE_TYPR_TRANSFOR_ISCOME
                    || object1.getType() == Constant.MESSAGE_TYPR_TOPAYFOR) {
                return -1;
            } else if (object2.getType() == Constant.MESSAGE_TYPR_TRANSFOR_ISCOME
                    || object2.getType() == Constant.MESSAGE_TYPR_TOPAYFOR) {
                return 1;
            } else if (object1.getIstop() == Constant.TOP_MAN) {
                if (object2.getIstop() == Constant.TOP_MAN) {
                    //时间
                    if (m1 < m2) {
                        return 1;
                    }
                    return -1;
                } else {
                    return -1;
                }
            } else if (object2.getIstop() == Constant.TOP_MAN) {
                return 1;
            } else {
                //时间
                if (m1 < m2) {
                    return 1;
                }
                return -1;
            }
        }
    }

    /**
     * 接受广播，刷新页面
     *
     * @param code
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void showNum(Integer code) {//chat页面返回
        if (code == Constant.MAIN_BOTTOM_TIP_NUM) {
            Log.i(TAG, "showNum: ==goto===getDataAtThread===001=======");
            getDataAtThread(null);
        } else if (code == Constant.BLACK_MESSAGE_REFRESH) {

            for (int i = 0; i < messageEntivities.size(); i++) {
                MessageEntivity imMessage = messageEntivities.get(i);
                Log.i(TAG, "showNum1: ==========" + imMessage.toString());
            }
            messageEntivities2.clear();
            messageEntivities2.addAll(messageEntivities);
            mMessageAdpter.refresh(messageEntivities2);
            ((MainActivity) getActivity()).showActivityMsgNum();

        }
    }

    /**
     * 接受广播，刷新页面
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updateUI(EventBusTypeObject event) {//chat页面返回
        if (null != event) {
            int type = event.getType();
            String types = "";
            switch (type) {
                case EventBusType.REFRESH_TYPE_ONE://修改备注名，测试通过
                    if (event.getSessiontype().equals("" + Constant.FROM_TYPE_MAM)) {
                        types = "_";
                    } else if (event.getSessiontype().equals("" + Constant.FROM_TYPE_GROUP)) {
                        types = "__";
                    }
                    List<MessageEntivity> udmessageEntivities = MessageEntivity.find(MessageEntivity.class
                            , "fromid=? and destid =? and uniqueness=?", ToolsUtils.getMyUserId() + "", event.getUid(), types);
                    if (null != udmessageEntivities && udmessageEntivities.size() > 0) {
                        MessageEntivity updatemsg = udmessageEntivities.get(0);
                        ImFriendEntivity imFriendEntivity = ToolsUtils.getMyFriendForId(Long.parseLong(event.getUid()));
                        if (null != imFriendEntivity && null != updatemsg)
                            updatemsg.setNick(imFriendEntivity.getRemark());
                        updatemsg.save();
                        if (null != messageEntivities2 && messageEntivities2.size() > 0) {
                            for (int i = 0; i < messageEntivities2.size(); i++) {
                                if (messageEntivities2.get(i).getUniqueness().equals(types)
                                        && ("" + messageEntivities2.get(i).getFromid()).equals(ToolsUtils.getMyUserId() + "")
                                        && ("" + messageEntivities2.get(i).getDestid()).equals(event.getUid())
                                        ) {
                                    messageEntivities2.set(i, updatemsg);
                                    mMessageAdpter.notifyItemChanged(i);
                                }
                            }
                        }
                    }
                    break;
            }
        }
    }

    @Override
    public void onMessageListClick(View view, int position) {
        doclickitem(position);
    }

    //此处所有过来的好友信息都是不全的需要通过好友id获取网络数据然后刷新界面最后存入数据库（添加好友是用）
    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onImessageThread(ImMessage imMessage) {
        if (imMessage.getFromType() == Constant.FROM_TYPE_SYS && imMessage.getMessageType() == Constant.MESSAGE_TYPR_BYE_FRIEND) {
            Log.i(TAG, "onImessageThread: 这里是删除操作啊");
            //清除消息列表数据
            MessageEntivity.deleteAll(MessageEntivity.class, "fromid=? and destid=? and from_type=?", new String[]{imMessage.getFromid() + "", imMessage.getDestid() + "", Constant.FROM_TYPE_MAM + ""});
            Log.i(TAG, "showNum: ==goto===getDataAtThread===002=======");
            getDataAtThread(null);
        }
    }

    @Override
    public void onMessageLongListClick(View view, final int position) {
        initMenu(view, false, 0, position);


    }

    /**
     * @param view
     * @param
     */
    public void initMenu(View view, final boolean ismarked, final int type, final int position) {

        popupMenu = new PopupMenu(getContext(), view);
        menu = popupMenu.getMenu();
        // 通过XML文件添加菜单项
        MenuInflater menuInflater = getActivity().getMenuInflater();
        menuInflater.inflate(R.menu.popup_menu_mark, menu);
        MenuItem item = menu.getItem(0);
        MenuItem item1 = menu.getItem(1);
//        final MessageEntivity messageEntivity = messageEntivities.get(position);
        final MessageEntivity messageEntivity = messageEntivities2.get(position);
        final long messageNum = messageEntivity.getMessageNum();
        if (messageNum != 0) {
            item.setTitle(getActivity().getResources().getString(R.string.read_yes_bj));
        } else {
            item.setTitle(getActivity().getResources().getString(R.string.read_no_bj));
        }
        //  Log.i("info","是否置顶=="+messageEntivity.toString());
        if (messageEntivity.getFromType() == 3){
            item1.setVisible(false);
        }else{
            item1.setVisible(true);
        }
        if (messageEntivity.getIstop() == 0) {

            item1.setTitle(getActivity().getResources().getString(R.string.set_top_yes));
        } else {
            item1.setTitle(getActivity().getResources().getString(R.string.set_top_no));
        }
        popupMenu.show();
        // 监听事件
        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.add_contacts://标记
                        MessageEntivity byId = MessageEntivity.findById(MessageEntivity.class, messageEntivity.getId());
                        if (messageNum != 0) {
                            byId.setMessageNum(0);
                        } else {
                            byId.setMessageNum(1);
                        }
                        byId.save();
                        EventBus.getDefault().post(Constant.MAIN_BOTTOM_TIP_NUM);
                        mMessageAdpter.notifyDataSetChanged();
                        break;
                    case R.id.search_group: //删除
                        if (messageEntivity.getFromType() == Constant.FROM_TYPE_SYS) {
                            if (messageEntivity.getType() == Constant.MESSAGE_TYPR_APPLY_FRIEND || messageEntivity.getType() == Constant.NOTICE_OF_APPLY_FRIEND) {
                                MessageEntivity.deleteAll(MessageEntivity.class, "fromid=? and (type=? or type=?)", messageEntivity.getFromid() + "", Constant.NOTICE_OF_APPLY_FRIEND + "", Constant.MESSAGE_TYPR_APPLY_FRIEND + "");
                            } else if (messageEntivity.getType() == Constant.MESSAGE_TYPR_TRANSFOR_ISCOME | messageEntivity.getType() == Constant.MESSAGE_TYPR_TOPAYFOR) {
                                MessageEntivity.deleteAll(MessageEntivity.class, "type=? or type=?", Constant.MESSAGE_TYPR_TRANSFOR_ISCOME + "", Constant.MESSAGE_TYPR_TOPAYFOR + "");
                            } else if (messageEntivity.getType() == Constant.MESSAGE_TYPR_GROUP_TRANS_ME) {
                                MessageEntivity.deleteAll(MessageEntivity.class, "fromid=? and type=?", messageEntivity.getFromid() + "", Constant.MESSAGE_TYPR_GROUP_TRANS_ME + "");
                            }else if(messageEntivity.getType() == Constant.MESSAGE_GROUP_ADD_APPLY){
                                MessageEntivity.deleteAll(MessageEntivity.class, "fromid=? and type=?", messageEntivity.getFromid() + "", Constant.MESSAGE_GROUP_ADD_APPLY + "");
                            }
                        } else {
                            MessageEntivity.delete(messageEntivity);
                        }
                        Log.i(TAG, "showNum: ==goto===getDataAtThread===003=======");
                        getDataAtThread(null);
                        break;
                    case R.id.scan: //置顶聊天
                        if (messageEntivity.getIstop() == 1) {
                            cancleTop(messageEntivity.getDestid() + "", messageEntivity.getFromType());
                        } else {
                            // Log.i("info","destid=="+messageEntivity.getDestid());
                            setTop(messageEntivity.getDestid() + "", messageEntivity.getFromType());
                        }
                        break;

                    default:
                        break;
                }
                return false;
            }
        });

    }

    public void setTop(final String destId, final int type) {
        // showProgress("设置中...");
        final UserEntivity userEntivity = ToolsUtils.getUser();
        mPGservice.setTop(destId, type + "", ToolsUtils.getMyUserId())
                .subscribe(new AbsAPICallback<ValidateEntivity>() {
                               @Override
                               protected void onResultError(ApiException ex) {
                                   new ToastUtils().showSingleToast(ex.getDisplayMessage());
                               }

                               @Override
                               public void onNext(ValidateEntivity data) {
                                   // ToolsUtils.showToast(getActivity(),data.getInfo());
                                   String types = "";
                                   if (type == Constant.FROM_TYPE_MAM) {
                                       types = "_";
                                   } else if (type == Constant.FROM_TYPE_GROUP) {
                                       types = "__";
                                   }
                                   // Log.i("info","destid=="+destId);
                                   List<MessageEntivity> messageEntivities = MessageEntivity.find(MessageEntivity.class, "fromid=? and destid =? and uniqueness=?", userEntivity.getId() + "", destId, types);
                                   // Log.i("info","message=="+messageEntivities);
                                   for (int i = 0; i < messageEntivities.size(); i++) {
                                       MessageEntivity messageEntivity = messageEntivities.get(i);
                                       //   Log.i("info",messageEntivity.toString());
                                       messageEntivity.setIstop(Constant.TOP_MAN);
                                       messageEntivity.save();
                                   }
                                   List<TipEntity> tipEntities = TipEntity.find(TipEntity.class, "user_id=? and dest_id =? and dest_type=?", userEntivity.getId() + "", destId, type + "");
                                   if (tipEntities.size() > 0) {
                                       EventBus.getDefault().post(Constant.MAIN_BOTTOM_TIP_NUM);
                                       // hideProgress();
                                       return;
                                   }
                                   //不存在置顶聊天，需要加入到置顶
                                   TipEntity tipEntity = new TipEntity();
                                   tipEntity.setDestId(destId);
                                   tipEntity.setUserId(userEntivity.getId() + "");
                                   tipEntity.setDestType(type);
                                   tipEntity.save();
                                   EventBus.getDefault().post(Constant.MAIN_BOTTOM_TIP_NUM);
                                   // hideProgress();
                               }
                           }
                );
    }

    /**
     * 取消置顶
     */
    private void cancleTop(final String destId, final int type) {
        // showProgress(getString(R.string.setting));
        final UserEntivity userEntivity = ToolsUtils.getUser();
        mPGservice.cancleTop(destId, type + "", ToolsUtils.getMyUserId()).subscribe(new AbsAPICallback<ValidateEntivity>() {
                                                                                        @Override
                                                                                        protected void onResultError(ApiException ex) {
                                                                                            showToast(ex.getDisplayMessage());
                                                                                        }

                                                                                        @Override
                                                                                        public void onNext(ValidateEntivity validateEntivity) {
                                                                                            String types = "";
                                                                                            if (type == Constant.FROM_TYPE_MAM) {
                                                                                                types = "_";
                                                                                            } else if (type == Constant.FROM_TYPE_GROUP) {
                                                                                                types = "__";
                                                                                            }
                                                                                            List<TipEntity> tipEntities = TipEntity.find(TipEntity.class, "user_id=? and dest_id =? and dest_type=?", userEntivity.getId() + "", destId, type + "");
                                                                                            for (int i = 0; i < tipEntities.size(); i++) {
                                                                                                tipEntities.get(i).delete();
                                                                                            }
                                                                                            List<MessageEntivity> messageEntivities = MessageEntivity.find(MessageEntivity.class, "fromid=? and destid =? and uniqueness=?", userEntivity.getId() + "", destId, types);
                                                                                            for (int i = 0; i < messageEntivities.size(); i++) {
                                                                                                MessageEntivity messageEntivity = messageEntivities.get(i);
                                                                                                messageEntivity.setIstop(Constant.TOP_NOT_MAN);
                                                                                                messageEntivity.save();
                                                                                            }
                                                                                            EventBus.getDefault().post(Constant.MAIN_BOTTOM_TIP_NUM);
                                                                                            //修改本地好友数据
                                                                                            //  hideProgress();
                                                                                            // showToast(validateEntivity.getInfo());
                                                                                        }
                                                                                    }

        );
    }

    @Override
    public void onclickcontent(int position) {
        messageList.getChildAt(position).setPressed(true);
        doclickitem(position);
    }

    private void doclickitem(int position) {
        if (position < 0) {
            return;
        }
//        MessageEntivity messageEntivity = messageEntivities.get(position);
        MessageEntivity messageEntivity = messageEntivities2.get(position);
        if (messageEntivity.getFromType() == Constant.FROM_TYPE_MAM) {//单人聊天
            Bundle bundle = new Bundle();
            bundle.putLong("destid", messageEntivity.getDestid());
            startActivityForResult(ChatActivity.class, Constant.MESSAGE_MAIN_GO_GROUP_RESULT, bundle);
//            Bundle bundle = new Bundle();
//            bundle.putLong("destid", messageEntivity.getDestid());
//            startActivityForResult(ChatListActivity.class, Constant.MESSAGE_MAIN_GO_GROUP_RESULT, bundle);
        } else if (messageEntivity.getFromType() == Constant.FROM_TYPE_GROUP) {
            Bundle bundle = new Bundle();
            ImGroupEntivity groupEntivity = ImGroupEntivity.findById(ImGroupEntivity.class, messageEntivity.getDestid());
            bundle.putSerializable("groupSeri", groupEntivity);
            long groupid = 0;
            if (null != groupEntivity && null != groupEntivity.getId()) {
                groupid = groupEntivity.getId();
            } else {
                groupid = messageEntivity.getDestid();
            }
            bundle.putLong("groupid", groupid);
            startActivity(ChatGroupActivity.class, bundle, false);
//            startActivity(ChatListGroupActivity.class, bundle, false);
        } else if (messageEntivity.getFromType() == Constant.FROM_TYPE_SYS) {//系统
            if (messageEntivity.getType() == Constant.MESSAGE_TYPR_APPLY_FRIEND ||
                    messageEntivity.getType() == Constant.NOTICE_OF_APPLY_FRIEND) {
                messageEntivity.setMessageNum(0);
                messageEntivity.save();
                startActivity(NewFriendsActivity.class);
            } else if (messageEntivity.getType() == Constant.MESSAGE_TYPR_TRANSFOR_ISCOME
                    | messageEntivity.getType() == Constant.NOTICE_OF_MONEY_ADD_FOR_JOIN_GROUP
                    | messageEntivity.getType() == Constant.NOTICE_OF_MONEY_REDUCE_JOIN_GROUP
                    | messageEntivity.getType() == Constant.MESSAGE_TYPR_TOPAYFOR) {
                messageEntivity.setMessageNum(0);
                messageEntivity.save();
                EventBus.getDefault().post(Constant.MAIN_BOTTOM_TIP_NUM);
                startActivity(AccountActivity.class);
            } else if (messageEntivity.getType() == Constant.MESSAGE_TYPR_GROUP_TRANS_ME || messageEntivity.getType() == Constant.MESSAGE_GROUP_ADD_APPLY) {//转让群
                messageEntivity.setMessageNum(0);
                messageEntivity.save();
                EventBus.getDefault().post(Constant.MAIN_BOTTOM_TIP_NUM);
                startActivity(GroupTransActivity.class);
            }
        }
    }
}
